package com.buildings.activity.reinforce;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.buildings.api.Api;
import com.buildings.util.CustomToast;
import com.buildings.util.SPUtil;
import com.bumptech.glide.Glide;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;

/**
 * @author shiyaolei
 * @packager com.buildings.activity.reinforce
 * @date 2020/8/31
 **/
public class UploadImage {

    private List<String> images;

    private String buildingCode;
    private String taskId = "111";

    private boolean isDelete = false;

    private Context context;

    public UploadImage(List<String> images, String buildingCode, Context context) {
        this.images = images;
        this.buildingCode = buildingCode;
        this.context = context;
    }

    public static final class Builder {

        private Context context;
        private List<String> images;
        private String buildingCode;

        public Builder context(Context context) {
            this.context = context;
            return this;
        }

        public Builder setImages(List<String> images) {
            this.images = images;
            return this;
        }

        public Builder setBuildingCode(String buildingCode) {
            this.buildingCode = buildingCode;
            return this;
        }

        public UploadImage build() {
            return new UploadImage(images, buildingCode, context);
        }
    }

    public void upLoadImages(Callback callback) {

        if (context == null) {
            return;
        }
        if (TextUtils.isEmpty(buildingCode)) {
            CustomToast.showToast(context, "建筑编码为空，不能上传图片");
            callback.onFailure(null, null);
            return;
        }

        if (images == null || images.size() == 0) {
            return;
        }

        MultipartBody.Builder multipartBodyBuilder =
                new MultipartBody.Builder().setType(MultipartBody.FORM)
                        .addFormDataPart("buildingCode", buildingCode + "")
                        .addFormDataPart("taskId", taskId + "");

        List<File> files = new ArrayList<>();
        for (String url : images) {
            if (url.startsWith("http://39.99.134.59")) {
                continue;
            }
            File file = new File(url);
            if (file.exists()) {
                files.add(file);
                RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
                multipartBodyBuilder.addFormDataPart("multipartFiles", url, requestBody);
              //todo 加进度条
//              multipartBodyBuilder.addFormDataPart("multipartFiles", url, createCustomRequestBody(MultipartBody.FORM, file, new ProgressListener() {
//                @Override
//                public void onProgress(long totalBytes, long remainingBytes, boolean done) {
//                  if (done) {
//                    Log.e("wangchao", totalBytes + "=====" + remainingBytes + "-----" + done);
//                    //EventBus.getDefault().post(new MessageEvent(""));
//                  }
//                }
//              }));
            }
        }

        if (files.size() == 0) {
            callback.onFailure(null, null);
            files.clear();
            return;
        }

        MultipartBody multipartBody = multipartBodyBuilder.build();

        String token = (String) SPUtil.get("token", "");
        final Request request = new Request.Builder().addHeader("token", token)
                .url(Api.UPLOAD_REINFORCE)
                .post(multipartBody)
                .build();

        OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
        httpBuilder.readTimeout(20000, TimeUnit.SECONDS)
                .connectTimeout(20000, TimeUnit.SECONDS)
                .writeTimeout(20000, TimeUnit.SECONDS);

        OkHttpClient okHttpClient = httpBuilder.build();

        okHttpClient.newCall(request).enqueue(callback);
    }

  public static RequestBody createCustomRequestBody(final MediaType contentType, final File file, final ProgressListener listener) {
    return new RequestBody() {
      @Override
      public MediaType contentType() {
        return contentType;
      }

      @Override
      public long contentLength() {
        return file.length();
      }

      @Override
      public void writeTo(BufferedSink sink) throws IOException {
        Source source;
        try {
          source = Okio.source(file);
          //sink.writeAll(source);
          Buffer buf = new Buffer();
          Long remaining = contentLength();
          for (long readCount; (readCount = source.read(buf, 2048)) != -1; ) {
            sink.write(buf, readCount);
            listener.onProgress(contentLength(), remaining -= readCount, remaining == 0);
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    };
  }

  interface ProgressListener {
    void onProgress(long totalBytes, long remainingBytes, boolean done);
  }
}
